#include <QMenu>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QDesktopServices>
#include <QXmlSimpleReader>
#include <QMessageBox>
#include <QSettings>
#include <QDebug>
#include "mainwindow.h"
#include "xmlhandler.h"
#include "settingsdialog.h"
#include "aboutdialog.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), manager(new QNetworkAccessManager(this)), tray(new QSystemTrayIcon(QIcon(":/evolution.png"), this))
{
    this->setupUi(this);
    QMenu* menu = new QMenu;
    QAction* settingsaction = new QAction(tr("Settings"), menu);
    QAction* aboutaction = new QAction(tr("About"), menu);
    QAction* quit = new QAction(tr("Quit"), menu);
    menu->addAction(settingsaction);
    menu->addSeparator();
    menu->addAction(aboutaction);
    menu->addAction(quit);

    connect(quit, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
    connect(settingsaction, SIGNAL(triggered()), this, SLOT(showSettings()));
    connect(aboutaction, SIGNAL(triggered()), this, SLOT(showAbout()));

    tray->setContextMenu(menu);
    tray->show();

    this->loadSettings();

    if(email.isEmpty() || password.isEmpty()) {
        this->showSettings();
        this->loadSettings();
    }

    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
    this->updateContactList();
}

void MainWindow::showAbout() {
    aboutDialog about;
    about.exec();
}

MainWindow::~MainWindow() {}

void MainWindow::loadSettings() {
    QSettings settings("dmitryduka", "ContactsList");
    email = settings.value("email", QString()).toString();
    password = settings.value("password", QString()).toString();
    if(settings.value("open", "browser").toString() == "browser") open = "https://mail.google.com/mail?view=cm&tf=0&to=";
    else open = "mailto:";
}

void MainWindow::showSettings() {
    settingsDialog settings;
    settings.exec();
    this->loadSettings();
    auth.clear();
    error.clear();
    this->updateContactList();
}

void MainWindow::updateContactList() {
    contacts.clear();
    error.clear();
    if(auth.isEmpty()) {
        QNetworkRequest request;
        request.setUrl(QUrl(g_api));
        request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(g_content_type));
        QByteArray search = "&Email=" + email.toAscii() + "&Passwd=" + password.toAscii() + "&service=cp&source=dmitryduka-contactslist-1";
        reply = manager->post(request, search);
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotError(QNetworkReply::NetworkError)));
    } else {
        QNetworkRequest request;
        request.setUrl(QUrl(g_contacts_url.arg(email)));
        request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(g_content_type));
        request.setRawHeader(g_auth_header.toAscii(), g_auth_value.arg(auth).toAscii());
        reply = manager->get(request);
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotError(QNetworkReply::NetworkError)));
    }
}

void MainWindow::slotError(QNetworkReply::NetworkError) {
    error = reply->errorString();
    tray->showMessage(tr("Connection error"), error, QSystemTrayIcon::Critical, 5000);
}

void MainWindow::replyFinished(QNetworkReply* reply) {
    if(reply->error() == QNetworkReply::NoError) {
        if(auth.isEmpty()) {
            while(!reply->atEnd()) {
                auth = reply->readLine();
                QStringList prms = auth.split('=');
                if(prms.size() == 2 && prms.at(0) == g_auth) {
                    auth = prms.at(1);
                }
            }
            if(auth.isEmpty()) tray->showMessage(tr("Contacts List"), tr("Unable to authorize on Google."), QSystemTrayIcon::Critical, 3000);
            else this->updateContactList();
        } else {
            QXmlSimpleReader xmlReader;
            QXmlInputSource source;
            source.setData(reply->readAll());
            xmlHandler* hndlr = new xmlHandler(contacts);
            xmlReader.setContentHandler(hndlr);
            xmlReader.setErrorHandler(hndlr);
            xmlReader.parse(source);
            tray->showMessage(tr("Contacts List"), tr("Recevied contacts list"), QSystemTrayIcon::Information, 1000);
        }
        delete reply;
    }
}

void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    QMenu* menu = NULL;
    switch (reason) {
    case QSystemTrayIcon::Trigger:
    case QSystemTrayIcon::DoubleClick:
        menu = new QMenu;
        if(error.isEmpty()) {
            foreach(QString name, contacts.keys()) {
                QAction* act = new QAction(name, menu);
                connect(act, SIGNAL(triggered()), this, SLOT(sendMail()));
                menu->addAction(act);
            }
            menu->popup(tray->geometry().bottomLeft());
        }
        break;
    default: ;
    }
}

void MainWindow::sendMail() {
    QString name = qobject_cast<QAction*>(QObject::sender())->text();
    QDesktopServices::openUrl(QUrl(open + contacts[name]));
}

